import {
	defineStore
} from 'pinia';
import {
	formatTime
} from './im/index'
import {
	decodeElement
} from './im/decodeElement'
import dayjs from 'dayjs';

const im = defineStore({
	id: 'im',
	state: () => ({
		isReady: false, // sdk 是否准备完成
		userInfo: null, // 当前用户的信息
		networkStatus: 'connected', // 网络状态 connected 正常 connecting 连接中  disconnected 网络不可用
		messageList: [], // 聊天首页列表
		message_Request: true, // 请求聊天列表状态
		keyword: '', // 首页搜索
		isFriend: false, // 单聊是否是好友
		type: '', // 当前增加的消息类型  chat = 私聊   group = 群聊
		chatInfo: {}, // 单聊的详细信息对象
		groupInfo: {}, // 群聊的详细信息对象
		chatMessageList: [], //单聊的聊天记录
		groupMessageList: [], // 群聊的聊天记录
		chatNextId: '', // 单聊的 --- 下一条消息标志
		chatComplete: false, // 单聊的 --- 当前会话消息是否已经请求完毕
		chatLoading: false, // 单聊的 --- 是否正在请求
		groupNextId: '',
		groupComplete: false,
		groupLoading: false,
		myGroupList: [], //我的群组
		unreadCount: '', // 好友申请未读数量
		isSystem: false ,// 是否是钱包助手或者订单助手
		mobile:'', //用户的手机账号
		to:'',
		statusBarHeight:''
	}),
	actions: {
		logAgain() {
			let self =this
			uni.showModal({
				title: '提示',
				content: '此账号已在别处登录，是否重新登录!',
				cancelText: '返回首页',
				confirmText: '重新登录',
				success(res) {
					if (res.confirm) {
						// 重新跳转到聊天首页 进行登录
						uni.reLaunch({
							url:`/pages/im/index?mobile=${self.mobile}&udid=${uni.getStorageSync('udid')}&to=${self.to}`
						})
					} else if (res.cancel) {
						// 返回小程序首页 根据不同的平台标识 跳转到不同的首页
						if (uni.getStorageSync('udid') === 'zjf') {
							window.jWeixin.miniProgram.switchTab({
								url:'/pages/index/index'
							})
						}
						if (uni.getStorageSync('udid') === 'mc') {
							window.jWeixin.miniProgram.switchTab({
								url:'/pages/index/home'
							})
						}
						if (uni.getStorageSync('udid') === 'hl') {
							window.jWeixin.miniProgram.switchTab({
								url:'/pages/index/home'
							})
						}
					}
				}
			});
		},
		setTalkList(id) {
			this.messageList = this.messageList.map(item => {
				if (item.account === id) {
					item.unreadCount = 0
				}
				return item
			})
		},
		// 我的群聊列表
		setMyGroup(data) {
			this.myGroupList = data
		},
		getGroupInfo(conversationID, type = true) {
			let self = this
			wx.$app.setMessageRead({
				conversationID
			})
			self.resetGroup()
			self.setTalkList(conversationID.split('GROUP')[1])
			wx.$app.getConversationProfile(conversationID).then(res => {
				if (res.code === 0) {
					self.groupInfo = res.data.conversation
					if (type) {
						let name = res.data.conversation.groupProfile.name || res.data.conversation
							.groupProfile.groupID
						self.getGroupMessageList()
						uni.navigateTo({
							url: `/pages/im/groupChat?title=${name}&isPinned=${self.groupInfo.isPinned}`
						})
					}
				}
			})
		},
		// 获取会话资料  有两种方式  一个群聊里的成员  一个是好友列表的
		getFriendInfo(conversationID, type) {
			let self = this
			self.resetChat()
			wx.$app.setMessageRead({
				conversationID
			})
			self.setTalkList(conversationID.split('C2C')[1])
			self.checkFriend(conversationID.split('C2C')[1])
			wx.$app.getConversationProfile(conversationID).then(res => {
				if (res.code === 0) {
					self.chatInfo = res.data.conversation
					let name = res.data.conversation.userProfile.nick || res.data
						.conversation.userProfile.userID
					uni.navigateTo({
						url: `/pages/im/userInfo?title=${name}&type=${type}`
					})
				}
			})
		},
		checkFriend(userId) {
			return new Promise((resolve, reject) => {
				wx.$app.checkFriend({
					userIDList: [userId],
					type: wx.TIM.TYPES.SNS_CHECK_TYPE_BOTH,
				}).then(res => {
					if (res.code === 0 && res.data.successUserIDList[0] && res.data
						.successUserIDList[0]
						.relation !== 'CheckResult_Type_BothWay') {
						this.isFriend = true
					} else {
						this.isFriend = false
					}
					resolve()
				})
			})
		},
		pushChatMessageList(message, type = 'chat') {
			message.lastMessage = decodeElement(message)
			let date = new Date(message.time * 1000)
			message.newtime = formatTime(date)
			message.status = 'success'
			message.timeString = dayjs(message.time * 1000).format('YYYY-MM-DD HH:mm:ss');
			if (type === 'chat') {
				this.chatMessageList.unshift(message)
			} else {
				this.groupMessageList.unshift(message)
			}
			setTimeout(() => {
				uni.pageScrollTo({
					scrollTop: 99999
				})
			}, 100)
			this.getMessageList()
		},
		// 会话资料
		async getChatInfo(conversationID, type, account) {
			let self = this
			self.type = type
			// 将会话消息设置为已读
			wx.$app.setMessageRead({
				conversationID
			})
			// 是否是好友
			if (self.type === 'chat') {
				self.resetChat()
				if (account !== "wallet" && account !== "order") {
					self.checkFriend(conversationID.split('C2C')[1])
				} else {
					self.isSystem = true
				}
				// 将列表的聊天标识设置已读
				self.setTalkList(conversationID.split('C2C')[1])
			} else {
				self.resetGroup()
				self.setTalkList(conversationID.split('GROUP')[1])
			}
			// 获取资料
			wx.$app.getConversationProfile(conversationID).then(res => {
				if (res.code === 0) {
					if (self.type === 'chat') {
						self.chatInfo = res.data.conversation
						self.getChatMessageList()
					} else {
						self.groupInfo = res.data.conversation
						self.getGroupMessageList()
					}
					let name = ''
					if (self.type === 'chat') {
						name = res.data.conversation.userProfile.nick || res.data.conversation
							.userProfile.userID
						uni.navigateTo({
							url: `/pages/im/chat?title=${name}&isPinned=${self.chatInfo.isPinned}`
						})
					} else {
						name = res.data.conversation.groupProfile.name || res.data.conversation
							.groupProfile.groupID
						uni.navigateTo({
							url: `/pages/im/groupChat?title=${name}&isPinned=${self.groupInfo.isPinned}`
						})
					}
				}
			})
		},
		// 私聊记录
		getChatMessageList() {
			let self = this
			const nextReqMessageID = self.chatNextId
			if (!self.chatComplete) {
				// 如果请求还没回来，又拉，此时做一下防御
				if (!this.chatLoading) {
					this.chatLoading = true
					this.getChatHistory().then(res => {
						if (res.length === 0) {
							this.chatComplete = true
							if (this.chatMessageList.length > 0) {
								uni.showToast({
									title: '没有更多啦',
									icon: 'none',
									duration: 1500
								})
							}
						} else {
							this.chatNextId = res[res.length - 1].id
							this.unshiftMessageList(res)
						}
						this.chatLoading = false
					}).catch(err => {
						console.log(err)
					})
				} else {
					uni.showToast({
						title: '你拉的太快了',
						icon: 'none',
						duration: 500
					})
				}
			} else {
				uni.showToast({
					title: '没有更多啦',
					icon: 'none',
					duration: 1500
				})
			}
		},
		// 群聊记录
		getGroupMessageList() {
			let self = this
			const nextReqMessageID = self.groupNextId
			if (!self.groupComplete) {
				// 如果请求还没回来，又拉，此时做一下防御
				if (!this.groupLoading) {
					this.groupLoading = true
					this.getGroupHistory().then(res => {
						if (res.length === 0) {
							this.groupComplete = true
							if (this.groupMessageList.length > 0) {
								console.log(1)
								uni.showToast({
									title: '没有更多啦',
									icon: 'none',
									duration: 1500
								})
							}
						} else {
							this.groupNextId = res[res.length - 1].id
							this.unshiftMessageList(res)
						}
						this.groupLoading = false
					}).catch(err => {
						console.log(err)
					})
				} else {
					uni.showToast({
						title: '你拉的太快了',
						icon: 'none',
						duration: 500
					})
				}
			} else {
				uni.showToast({
					title: '没有更多啦',
					icon: 'none',
					duration: 1500
				})
			}
		},
		unshiftMessageList(messageList) {
			let list = [...messageList]
			for (let i = 0; i < list.length; i++) {
				let message = list[i]
				list[i].lastMessage = decodeElement(message)
				let date = new Date(message.time * 1000)
				list[i].newtime = formatTime(date)
				list[i].newtime = date
			}
			if (this.type === 'chat') {
				this.chatMessageList = [...this.chatMessageList, ...list]
			} else {
				this.groupMessageList = [...this.groupMessageList, ...list]
			}
			console.log(this.chatMessageList)
		},
		// 设置状态
		async setIsReady(data) {
			this.isReady = data
			if (this.isReady) {
				if (!this.userInfo) {
					await this.getMyUserInfo()
				} else {
					this.getMessageList()
				}
			}
		},
		// 获取首页会话列表
		getMessageList() {
			let self = this
			self.messageList = []
			self.message_Request = true
			uni.request({
				url: 'https://im-beta.shisan-xi.work/api/settings/talkList',
				data: {
					mobile: this.userInfo.userID,
					platform: uni.getStorageSync('udid'),
					keyword: this.keyword
				},
				success({
					data
				}) {
					self.messageList = data.data.map(obj => ({
						account: obj.account,
						conversationID: (obj.type == 'user' ? 'C2C' : 'GROUP') + obj
							.account,
						type: obj.type == 'user' ? 'C2C' : 'GROUP',
						unreadCount: obj.unreadNum,
						from: obj.from_account,
						[obj.type == 'user' ? 'userProfile' : 'groupProfile']: {
							[obj.type == 'user' ? 'userID' : 'groupID']: obj.account,
							[obj.type == 'user' ? 'nick' : 'name']: obj.type == 'user' ? obj
								.info.Tag_Profile_IM_Nick : obj.info.Name,
							avatar: obj.type == 'user' ? obj.info.Tag_Profile_IM_Image : obj
								.info.FaceUrl
						},
						lastMessage: {
							fromAccount: obj.last_msg.from_account,
							lastTime: obj.last_msg.create_time,
							messageForShow: obj.last_msg.msg_body.MsgType ===
								'TIMCustomElem' ? self.resetMessage(obj) : obj.last_msg
								.msg_content,
							type: obj.last_msg.msg_body.MsgType
						},
					}))
					self.message_Request = false
				}
			})
		},
		resetMessage(msg) {
			// 钱包助手/订单信息
			if (msg.type === 'user') {
				if (msg.account === "wallet") {
					let obj = JSON.parse(msg.last_msg.msg_content)
					return obj.money_msg
				}
				if (msg.account === "order") {
					let obj =  JSON.parse(msg.last_msg.msg_content)
					return obj.order_status_title
				}
			} else {
				// 群聊自定义消息
			}
			return ''
		},
		// 获取用户信息
		getMyUserInfo() {
			let self = this
			wx.$app.getMyProfile().then(res => {
				self.userInfo = res.data
				// 修改用户添加好友的通过方式
				if (res.data.allowType !== 'AllowType_Type_NeedConfirm') {
					wx.$app.updateMyProfile({
						allowType: 'AllowType_Type_NeedConfirm'
					}).then(imResponse => {
						self.userInfo = imResponse.data
					})
				}
				self.getMessageList()
			})
		},
		setNetwork(data) {
			this.networkStatus = data
		},
		showNetwork() {
			if (this.networkStatus === 'disconnected') {
				uni.showModal({
					title: '提示',
					content: '当前网络不可用',
				});
			}

			if (this.networkStatus === 'connecting') {
				uni.showModal({
					title: '提示',
					content: '当前网络不稳定',
				});
			}
		},
		setKeyword(data) {
			this.keyword = data
		},
		getGroupHistory() {
			let self = this
			return new Promise(async (resolve, reject) => {
				let memberList = []
				let {
					data
				} = await wx.$app.getGroupMemberList({
					groupID: self.groupInfo.groupProfile.groupID
				})
				memberList = data.memberList
				uni.request({
					url: 'https://im-beta.shisan-xi.work/api/settings/talkDetail',
					data: {
						mobile: self.userInfo.userID,
						last_id: self.groupNextId || '',
						group_id: self.groupInfo.groupProfile.groupID
					},
					success: ({
						data
					}) => data.code == 1 ? resolve(data.data.list.map(obj => ({
						id: obj.id,
						conversationID: self.groupInfo.groupProfile.groupID,
						conversationType: self.groupInfo.type,
						userID: obj.from_account,
						status: 'success',
						isPeerRead: !!obj.is_read,
						time: obj.create_time.replace(/-/g, '/'),
						timeString: obj.create_time,
						type: obj.msg_body.MsgType,
						from: obj.from_account,
						flow: (obj.from_account == self.userInfo.userID) ?
							'out' : 'in',
						nick: (memberList.find(v => v.userID == (obj
							.from_account == 'administrator' ?
							memberList.find(a => a.role ==
								"Owner").userID : obj
							.from_account))?.nick || ''),
						avatar: (memberList.find(v => v.userID == (obj
							.from_account == 'administrator' ?
							memberList.find(a => a.role ==
								"Owner").userID : obj
							.from_account))?.avatar || ''),
						payload: {
							[obj.msg_body.MsgType == 'TIMImageElem' ?
								'imageInfoArray' :
								obj.msg_body.MsgType == 'TIMSoundElem' ?
								'url' :
								obj.msg_body.MsgType == 'TIMFaceElem' ?
								'data' :
								obj.msg_body.MsgType == 'TIMVideoFileElem' ?
								'videoUrl' : 'text'
							]: obj.msg_body.MsgType == 'TIMImageElem' ? obj
								.msg_body.MsgContent.ImageInfoArray.map(
									img => ({
										url: img.URL
									})) : obj.msg_body.MsgType ==
								'TIMSoundElem' ? obj.msg_body.MsgContent
								.Url : obj.msg_body.MsgType ==
								'TIMFaceElem' ? obj.msg_body.MsgContent
								.Data : obj.msg_body.MsgType ==
								'TIMVideoFileElem' ? obj.msg_body.MsgContent
								.VideoUrl : obj.msg_body.MsgContent.Text,
							[obj.msg_body.MsgType == 'TIMSoundElem' ?
								'second' :
								obj.msg_body.MsgType == 'TIMVideoFileElem' ?
								'videoUrlimg' : 'type'
							]: obj.msg_body.MsgType == 'TIMSoundElem' ? obj
								.msg_body.MsgContent.Second : obj.msg_body
								.MsgType == 'TIMVideoFileElem' ? obj
								.msg_body.MsgContent.VideoUrl +
								'?ci-process=snapshot&time=0.01' : obj
								.msg_body.MsgType
						}
					}))) : reject(data),
					fail: () => reject(false)
				})
			})
		},
		getChatHistory() {
			let self = this
			return new Promise(async (resolve, reject) => {
				uni.request({
					url: 'https://im-beta.shisan-xi.work/api/settings/talkDetail',
					data: {
						mobile: self.userInfo.userID,
						last_id: self.chatNextId || '',
						account: self.chatInfo.userProfile.userID
					},
					success: ({
						data
					}) => data.code == 1 ? resolve(data.data.list.map(obj => ({
						id: obj.id,
						to: self.userInfo.userID,
						conversationID: self.chatInfo.userProfile.userID,
						conversationType: self.chatInfo.type,
						userID: obj.from_account,
						status: 'success',
						isPeerRead: !!obj.is_read,
						time: obj.create_time.replace(/-/g, '/'),
						timeString: obj.create_time,
						type: obj.msg_body.MsgType,
						from: obj.from_account,
						flow: (obj.from_account === self.userInfo.userID) ?
							'out' : 'in',
						nick: (obj.from_account == self.userInfo.userID) ?
							self.userInfo.nick : self.chatInfo.userProfile
							.nick,
						avatar: (obj.from_account == self.userInfo.userID) ?
							self.userInfo.avatar : self.chatInfo.userProfile
							.avatar,
						payload: {
							[obj.msg_body.MsgType == 'TIMImageElem' ?
								'imageInfoArray' :
								obj.msg_body.MsgType == 'TIMSoundElem' ?
								'url' :
								obj.msg_body.MsgType == 'TIMFaceElem' ?
								'data' :
								obj.msg_body.MsgType == 'TIMVideoFileElem' ?
								'videoUrl' : obj.msg_body.MsgType ==
								'TIMCustomElem' ? 'custom' : 'text'
							]: obj.msg_body.MsgType == 'TIMImageElem' ? obj
								.msg_body.MsgContent.ImageInfoArray.map(
									img => ({
										url: img.URL
									})) : obj.msg_body.MsgType ==
								'TIMSoundElem' ? obj.msg_body.MsgContent
								.Url : obj.msg_body.MsgType ==
								'TIMFaceElem' ? obj.msg_body.MsgContent
								.Data : obj.msg_body.MsgType ==
								'TIMVideoFileElem' ? obj.msg_body.MsgContent
								.VideoUrl : obj.msg_body.MsgType == 'TIMCustomElem' ? JSON.parse(obj.msg_body.MsgContent.Data) : obj.msg_body.MsgContent.Text,
							[obj.msg_body.MsgType == 'TIMSoundElem' ?
								'second' :
								obj.msg_body.MsgType == 'TIMVideoFileElem' ?
								'videoUrlimg' : 'type'
							]: obj.msg_body.MsgType == 'TIMSoundElem' ? obj
								.msg_body.MsgContent.Second : obj.msg_body
								.MsgType == 'TIMVideoFileElem' ? obj
								.msg_body.MsgContent.VideoUrl +
								'?ci-process=snapshot&time=0.01' : obj
								.msg_body.MsgType
						}
					}))) : reject(data),
					fail: () => reject(false)
				})
			})
		},
		// 重置数据
		resetChat() {
			this.isFriend = false
			this.chatInfo = {}
			this.chatMessageList = []
			this.chatNextId = ''
			this.chatComplete = false
			this.chatLoading = false
			this.isSystem = false
		},
		resetGroup() {
			this.groupInfo = {}
			this.groupMessageList = []
			this.groupNextId = ''
			this.groupComplete = false
			this.groupLoading = false
		},
		imLogin(mobile) {
			return new Promise((resolve, reject) => {
				uni.request({
					url: 'https://im-beta.shisan-xi.work/api/settings/getUser',
					method: 'POST',
					data: {
						mobile: mobile
					},
					success: (result) => {
						uni.request({
							url: 'https://im-beta.shisan-xi.work/api/settings/createSign',
							data: {
								identifier: result.data.data.im_id
							},
							success: (res) => {
								wx.$app.login({
									userID: result.data.data.im_id,
									userSig: res.data.data.userSig
								}).then((response) => {
									resolve()
								}).catch((err) => {
									reject()
								})
							}
						});
					}
				});

			})
		},
	},
	persist: {
		enabled: true,
		strategies: [{
			key: 'im-store',
		}, ],
	},
});

export default im;